const express = require('express')
const router = express.Router()
const upload = require('../utils/multer')
const path = require('path')
const fs = require('fs')

// 图片上传
router.post('/upload', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '请选择要上传的图片' })
  }
  
  const imageUrl = `/uploads/${req.file.filename}`
  res.json({ 
    success: true,
    url: imageUrl,
    filename: req.file.filename
  })
})

// 获取图片列表
router.get('/images', (req, res) => {
  const uploadDir = path.join(__dirname, '../uploads')
  fs.readdir(uploadDir, (err, files) => {
    if (err) {
      return res.status(500).json({ error: '无法读取图片目录' })
    }
    
    const images = files.filter(file => 
      ['.jpg', '.jpeg', '.png'].includes(path.extname(file).toLowerCase())
    ).map(file => ({
      url: `/uploads/${file}`,
      filename: file
    }))
    
    res.json(images)
  })
})

// 删除图片
router.delete('/images/:filename', (req, res) => {
  const filePath = path.join(__dirname, '../uploads', req.params.filename)
  
  fs.unlink(filePath, (err) => {
    if (err) {
      return res.status(404).json({ error: '图片不存在或删除失败' })
    }
    res.json({ success: true })
  })
})

module.exports = router